package com.u.social.sale.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.u.social.sale.entity.Order;
import com.u.social.sale.entity.OrderItems;
import com.u.social.sale.entity.Product;
import com.u.social.sale.entity.ProductSku;
import com.u.social.sale.mapper.OrderMapper;
import com.u.social.sale.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-03-10
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private IOrderItemsService orderItemsService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IProductStockService productStockService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addOrderByProduct(Long productId, Long skuId) {

         // 获取商品信息与sku信息
        Product product = productService.getById(productId);
        ProductSku productSku = productSkuService.getById(skuId);

        // 生成订单信息
        Order order = new Order();
        order.setOrderNo(IdUtil.getSnowflake().nextId());
        order.setOrderPrice(productSku.getPrice());
        save(order);

        OrderItems orderItem = new OrderItems();
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(productId);
        orderItem.setSkuId(skuId);
        orderItem.setProductName(product.getName());
        orderItem.setSkuAttributes(productSku.getSkuValue() + ":" + productSku.getSkuName());
        orderItem.setProductPrice(productSku.getPrice());
        orderItem.setQuantity(1);
        orderItem.setSubtotalPrice(productSku.getPrice());
        orderItemsService.save(orderItem);

        // 扣减库存
        productStockService.decreaseStock(productId, skuId, 1);

        // 返回整个订单信息
        return true;
    }

    @Override
    public Boolean addOrderByCart(Long userId) {
        return null;
    }
}
